package com.example.zyl.api.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.zyl.api.entity.OperateLog;
import com.example.zyl.api.entity.dto.OperateLogDto;
import com.example.zyl.api.mapper.OperateLogMapper;
import com.example.zyl.api.service.IOperateLogService;
import com.example.zyl.common.query.annotation.ApiDataSource;
import com.example.zyl.common.query.page.PageParam;
import com.example.zyl.common.utils.RedisUtils;
import com.example.zyl.common.utils.constant.RedisConstant;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 操作日志记录 服务实现类
 * </p>
 *
 * @author zyl
 * @since 2024-11-28
 */
@Service
@RequiredArgsConstructor
@ApiDataSource(name = "sbm")
public class OperateLogServiceImpl extends ServiceImpl<OperateLogMapper, OperateLog> implements IOperateLogService {

    private final OperateLogMapper operateLogMapper;

    private final RedisUtils redisUtils;

    @Override
    public Page<OperateLog> searchList(PageParam<OperateLog, OperateLogDto> pageParam) {
        //获取查询条件
        OperateLogDto operateLogDto = pageParam.getParam();
        //获取分页信息
        Page<OperateLog> page = pageParam.getPage();
        //构建查询条件
        QueryWrapper<OperateLog> wrapper = operateLogDto.defaultWrapper();
        //分页查询
        return operateLogMapper.selectPage(page, wrapper);
    }

    @Override
    public List<OperateLog> pageCacheList(PageParam<OperateLog, OperateLogDto> pageParam) {

        String redisKey = RedisConstant.REDIS_KEY_PREFIX;
        long current = pageParam.getPage().getCurrent();
        long size = pageParam.getPage().getSize();
        // 计算分页的偏移量和限制
        // 计算起始索引（start）和结束索引（end）
        long start = (current - 1) * size; // 起始索引
        long end = start + size - 1;  // 结束索引
        long l = redisUtils.lLen(redisKey);
        List<Object> objects = redisUtils.lRange(redisKey, start, end);
        return BeanUtil.copyToList(objects, OperateLog.class);
    }
}
